package com.ahj.apkupdata;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;

import androidx.core.content.FileProvider;

import java.io.File;

import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.PluginRegistry;

public class APKUpdataPlugin implements MethodChannel.MethodCallHandler {

    public static final String CHANNEL = "com.qingning.qn/APKUpdataPlugin";
    static MethodChannel channe;
    private Activity activity;

    public APKUpdataPlugin(Activity activity) {
        this.activity = activity;
    }

    public static void registerWith(FlutterEngine flutterEngine, Activity activity12) {
        channe = new MethodChannel(flutterEngine.getDartExecutor(), CHANNEL);
        APKUpdataPlugin plugin = new APKUpdataPlugin(activity12);
        channe.setMethodCallHandler(plugin);
    }

    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        try {
            if (methodCall.method.equals("install")) {
                String path = methodCall.argument("path");
                if (TextUtils.isEmpty(path)) {
                    result.success("");
                    return;
                }
                File apkFile = new File(path);
                // 获取文件Uri 根据系统来区分，7.0一下和7.0以上
                Uri uri = null;
                if (Build.VERSION.SDK_INT >= 24) {
                    //判读版本是否在7.0以上
                    uri = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileProvider", apkFile);
                } else {
                    // 版本在7.0一下
                    uri = Uri.fromFile(apkFile);
                }
                // 安装下载好的apk文件
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(uri, "application/vnd.android.package-archive");
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                // 这里的EcmobileApp.context是application的context
                activity.startActivity(intent);
            } else {
                result.notImplemented();
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.success("");
        }
    }
}
